#include "window.h"
#include "core.h"
#include "log.h"

window::window(xml_node& _node)
{
	m_hwnd = 0;

	m_width = _node.attr_int("width",800);
	m_height = _node.attr_int("height",600);
	m_fullscreen = _node.attr_bool("fullscreen",false);

	WNDCLASSEX wc;
	ZeroMemory(&wc, sizeof(wc));
	wc.cbSize = sizeof(wc);
	wc.hInstance = GetModuleHandle(NULL);
	wc.lpszClassName = "nEngine";
	wc.lpfnWndProc = wnd_proc;
	wc.style = CS_OWNDC;
	wc.hCursor = LoadCursor(NULL,IDC_ARROW);
	wc.hbrBackground = NULL;
	RegisterClassEx(&wc);

	if(m_fullscreen)
	{
		DEVMODE dm;
		EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
		m_width = dm.dmPelsWidth;
		m_height = dm.dmPelsHeight;
	}

	m_hwnd = CreateWindowEx(0,"nEngine","nEngine", 
		(m_fullscreen?WS_POPUP:WS_OVERLAPPEDWINDOW)|WS_CLIPCHILDREN|WS_CLIPSIBLINGS, 
		CW_USEDEFAULT,CW_USEDEFAULT,m_width,m_height,NULL,NULL,wc.hInstance,0);

	if(m_hwnd==0)
	{
		LOG_FATAL("Unable to create the window.");
	}

	if(m_fullscreen)
		SetWindowPos(m_hwnd,0,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);

	ShowCursor(TRUE);
	ShowWindow(m_hwnd,SW_SHOW);
	SetFocus(m_hwnd);
}

window::~window()
{
	close();
}

void window::close()
{
	if(m_hwnd!=0)
		CloseWindow(m_hwnd);
}

LRESULT CALLBACK window::wnd_proc(HWND _hwnd,u32 _msg,WPARAM _wparam,LPARAM _lparam)
{
	game* g = core::get_inst().get_game();

	switch(_msg)
	{
		case WM_KEYDOWN:
		{
			if(g)
			{
				g->event_keyboard(WM_KEYDOWN,_wparam);
			}
		}
		break;
		case WM_SYSCOMMAND:			
			switch (_wparam)		
			{
			case SC_SCREENSAVE:	
			case SC_MONITORPOWER:
				return 0;
			}
			break;

		case WM_CLOSE:
		case WM_DESTROY:
			PostQuitMessage(0);
			return 0;
			break;
	}

	return DefWindowProc(_hwnd,_msg,_wparam,_lparam);
}